<template>
    <view class="container">
        <!-- 公共模块，显示返回箭头和标题 -->
        <public-module leftIcon="arrow-left" :title="title" />
        <view class="header">
            <input class="title-input" v-model="paperInfo.paperName" placeholder="请输入试卷标题" />

            <view class="score-info">
                <view class="edit-field">
                    <text>分数:</text>
                    <input v-model.number="paperInfo.score" class="number-input" placeholder="请输入分数" />
                </view>

                <view class="edit-field">
                    <text>击败率:</text>
                    <input :value="displayValue(paperInfo.beatRate, '%')" @focus="handleFocus('beatRate')"
                        @blur="handleBlur('beatRate', '%')" @input="handleInput('beatRate', $event.detail.value, '%')"
                        class="number-input" placeholder="请输入击败比" />
                </view>

                <button class="submit-btn" @click="submitPaperInfo">
                    <u-icon name="file-text" size="20"/>
                    <text class="submit-text">提交</text>
                </button>
            </view>
        </view>

        <!-- 模块统计数据部分 -->
        <view class="module-stats">
            <view class="module-item" v-for="module in modules" :key="module.key">
                <text class="module-name">{{ module.name }}</text>
                <view class="module-data-container">
                    <text class="module-data-label">正确率:</text>
                    <input :value="displayValue(paperInfo[module.accuracyKey], '%')"
                        @focus="handleFocus(module.accuracyKey)" @blur="handleBlur(module.accuracyKey, '%')"
                        @input="handleInput(module.accuracyKey, $event.detail.value, '%')" class="number-input required-field"
                        placeholder=" %" />

                    <text class="module-data-label">用时:</text>
                    <input :value="displayValue(paperInfo[module.timeKey], 'min')" @focus="handleFocus(module.timeKey)"
                        @blur="handleBlur(module.timeKey, 'min')"
                        @input="handleInput(module.timeKey, $event.detail.value, 'min')" class="number-input required-field"
                        placeholder=" min" />
                </view>
            </view>
        </view>

        <!-- 整卷总结 -->
        <view class="summary fixed-bottom">
            <view class="summary-header">
                <text class="summary-title">整卷总结</text>
                <text class="word-count" :class="{ 'warning': isWordCountWarning, 'error': isWordCountError }">
                    {{ paperInfo.summary.length }}/{{ maxSummaryLength }}
                </text>
            </view>
            <textarea class="summary-edit" v-model="paperInfo.summary" placeholder="请在复盘的时候思考两个问题。\n 1、你为什么错？2、你为什么慢？\n以江苏A卷为例，想要达到70分，推荐的模块用时。\n政治5分钟，常识3分钟，言语25分钟，判断45分钟，资料30分钟，数推5分钟，剩下时间给数量运算和涂卡。"
                @input="handleSummaryInput" :maxlength="maxSummaryLength"></textarea>
        </view>
    </view>
</template>

<script>
    import {
        examReviewAdd
    } from "@/config/api.js";
    export default {
        data() {
            return {
                title: '新增复盘',
                paperInfo: {
                    paperName: '',
                    score: '',
                    beatRate: '',
                    politicsAccuracy: '',
                    politicsTime: '',
                    commonSenseAccuracy: '',
                    commonSenseTime: '',
                    languageAccuracy: '',
                    languageTime: '',
                    quantityAccuracy: '',
                    quantityTime: '',
                    judgmentAccuracy: '',
                    judgmentTime: '',
                    dataAccuracy: '',
                    dataTime: '',
                    summary: ''
                },
                modules: [{
                        key: 'politics',
                        name: '政治',
                        accuracyKey: 'politicsAccuracy',
                        timeKey: 'politicsTime'
                    },
                    {
                        key: 'commonSense',
                        name: '常识',
                        accuracyKey: 'commonSenseAccuracy',
                        timeKey: 'commonSenseTime'
                    },
                    {
                        key: 'language',
                        name: '言语',
                        accuracyKey: 'languageAccuracy',
                        timeKey: 'languageTime'
                    },
                    {
                        key: 'quantity',
                        name: '数量',
                        accuracyKey: 'quantityAccuracy',
                        timeKey: 'quantityTime'
                    },
                    {
                        key: 'judgment',
                        name: '判断',
                        accuracyKey: 'judgmentAccuracy',
                        timeKey: 'judgmentTime'
                    },
                    {
                        key: 'data',
                        name: '资料',
                        accuracyKey: 'dataAccuracy',
                        timeKey: 'dataTime'
                    }
                ],
                editingFields: {}, // 记录正在编辑的字段，用于临时存储不带单位的值
                maxSummaryLength: 1000, // 整卷总结最大字数限制
                isWordCountWarning: false, // 是否显示黄色警告
                isWordCountError: false, // 是否显示红色错误
                isMobile: uni.getWindowInfo().windowWidth < 768 // 检测是否为移动设备
            }
        },
        computed: {
            // 根据设备类型动态调整样式
            containerStyle() {
                return this.isMobile ? 'padding: 20rpx;' : 'padding: 40rpx; max-width: 1200rpx; margin: 0 auto;';
            },
            summaryHeight() {
                return this.isMobile ? 'calc(100vh - 450rpx - env(safe-area-inset-bottom))' : '300rpx';
            }
        },
        mounted() {
            // 监听窗口大小变化，更新设备类型
            uni.onWindowResize(() => {
                this.isMobile = uni.getWindowInfo().windowWidth < 768;
            });
        },
        methods: {
            // 显示带单位的值
            displayValue(value, unit) {
                if (this.editingFields[value] !== undefined) {
                    return this.editingFields[value];
                }
                // 确保只添加一个单位
                if (value && !value.endsWith(unit)) {
                    return value + unit;
                }
                return value || '';
            },

            // 处理输入框聚焦事件
            handleFocus(key) {
                // 保存当前值（不带单位）
                const value = this.paperInfo[key] || '';
                this.editingFields[key] = value.replace(new RegExp(unit + '$'), '');
            },

            // 处理输入框失焦事件
            handleBlur(key, unit) {
                let value = this.editingFields[key] || '';
                // 去除非数字字符
                value = value.replace(/[^\d.]/g, '');

                // 如果有值，添加单位（确保只添加一次）
                if (value) {
                    this.paperInfo[key] = value.endsWith(unit) ? value : value + unit;
                } else {
                    this.paperInfo[key] = '';
                }

                // 清除临时编辑值
                delete this.editingFields[key];
            },

            // 处理输入事件
            handleInput(key, value, unit) {
                // 只允许输入数字和小数点
                value = value.replace(/[^\d.]/g, '');
                this.editingFields[key] = value;
            },

            // 从值中移除单位
            removeUnit(value, unit) {
                if (!value) return '';
                return value.toString().replace(new RegExp(unit + '$'), '');
            },

            // 处理总结输入
            handleSummaryInput() {
                const length = this.paperInfo.summary.length;
                // 设置警告和错误状态
                this.isWordCountWarning = length > this.maxSummaryLength * 0.8;
                this.isWordCountError = length > this.maxSummaryLength;

                // 超过最大长度时截断（虽然textarea有maxlength属性，但还是保险起见）
                if (length > this.maxSummaryLength) {
                    this.paperInfo.summary = this.paperInfo.summary.substring(0, this.maxSummaryLength);
                    this.isWordCountError = false; // 截断后取消错误状态
                }
            },

            async submitPaperInfo() {
                // 添加表单验证
                if (!this.paperInfo.paperName) {
                    uni.showToast({
                        title: '请输入试卷标题',
                        icon: 'none'
                    });
                    return;
                }

                if (this.paperInfo.score === null || this.paperInfo.score === '') {
                    uni.showToast({
                        title: '请输入分数',
                        icon: 'none'
                    });
                    return;
                }

                if (!this.paperInfo.beatRate) {
                    uni.showToast({
                        title: '请输入击败比',
                        icon: 'none'
                    });
                    return;
                }

                // 验证模块统计数据（正确率和用时为必填项）
                for (let module of this.modules) {
                    const accuracyValue = this.removeUnit(this.paperInfo[module.accuracyKey], '%');
                    const timeValue = this.removeUnit(this.paperInfo[module.timeKey], 'min');
                    
                    if (!accuracyValue) {
                        uni.showToast({
                            title: `请输入${module.name}正确率`,
                            icon: 'none'
                        });
                        return;
                    }
                    
                    if (!timeValue) {
                        uni.showToast({
                            title: `请输入${module.name}用时`,
                            icon: 'none'
                        });
                        return;
                    }
                }

                try {
                    // 处理提交前的数据格式
                    const submitData = {
                        ...this.paperInfo
                    };

                    // 处理击败比，确保只有一个%
                    submitData.beatRate = this.removeUnit(submitData.beatRate, '%');
                    if (submitData.beatRate) submitData.beatRate += '%';

                    // 确保所有正确率和用时字段格式正确
                    this.modules.forEach(module => {
                        // 处理正确率
                        submitData[module.accuracyKey] = this.removeUnit(submitData[module.accuracyKey], '%');
                        if (submitData[module.accuracyKey]) submitData[module.accuracyKey] += '%';

                        // 处理用时 - 保留min后缀
                        submitData[module.timeKey] = this.removeUnit(submitData[module.timeKey], 'min');
                        if (submitData[module.timeKey]) {
                            // 确保用时保留min后缀
                            submitData[module.timeKey] = submitData[module.timeKey] + 'min';
                        }
                    });

                    const res = await examReviewAdd(submitData);
                    if (res.code === 200) {
                        uni.showToast({
                            title: '新增成功',
                            icon: 'success'
                        });
                        // 设置需要刷新标志
                        const pages = getCurrentPages();
                        const prevPage = pages[pages.length - 2];
                        if (prevPage && prevPage.route === 'pages/review/index') {
                            prevPage.$vm.needRefresh = true;
                        }

                        setTimeout(() => {
                            uni.navigateBack({
                                success: () => {
                                    // 通过事件总线触发刷新
                                    uni.$emit('refreshReviewList');
                                }
                            });
                        }, 1500);
                    } else {
                        uni.showToast({
                            title: res.msg || '新增失败',
                            icon: 'none'
                        });
                    }
                } catch (error) {
                    console.error('新增失败:', error);
                    uni.showToast({
                        title: '新增失败',
                        icon: 'none'
                    });
                }
            }
        }
    }
</script>

<style scoped>
    /* 基础样式 */
    .container {
        background-color: #f8f8f8;
    }

    .header {
        margin-bottom: 30rpx;
        padding: 20rpx;
        background-color: #fff;
        border-radius: 10rpx;
        box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
    }

    .title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
    }

    .score-info {
        margin-top: 20rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 20rpx;
        flex-wrap: nowrap;
    }

    .score-info text {
        font-size: 28rpx;
        color: #666;
        white-space: nowrap;
    }

    .module-stats {
        background-color: #fff;
        border-radius: 10rpx;
        box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
        overflow: hidden;
        margin-bottom: 0;
    }

    .module-item {
        padding: 12rpx 50rpx;
        display: flex;
        align-items: center;
    }

    .module-item:last-child {
        border-bottom: none;
    }

    .module-name {
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
        margin-right: 20rpx;
        display: flex;
        align-items: center;
    }

    .module-data-container {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
    }

    .module-data-label {
        font-size: 26rpx;
        color: #666;
        width: 75px;
        text-align: right;
        margin-right: 10rpx;
    }

    .module-data-value {
        font-size: 26rpx;
        color: #333;
        margin-right: 20rpx;
    }

    .summary {
        padding: 20rpx;
        background-color: #fff;
        border-radius: 0;
        box-shadow: 0 -2rpx 4rpx rgba(0, 0, 0, 0.1);
    }

    .summary-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .summary-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
    }

    .word-count {
        font-size: 24rpx;
        color: #999;
    }

    .word-count.warning {
        color: #ff9900;
    }

    .word-count.error {
        color: #ff3300;
    }

    .right-buttons {
        position: fixed;
        right: 20rpx;
        top: 50%;
        transform: translateY(-60%);
        display: flex;
        flex-direction: column;
        gap: 20rpx;
    }

    .add-like-btn,
    .add-collect-btn {
        background-color: transparent;
        border-radius: 0;
        width: auto;
        height: auto;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .save-icon-btn {
        background-color: #007AFF;
        color: #fff;
        border-radius: 50%;
        width: 60rpx;
        height: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 32rpx;
        margin-left: 10rpx;
    }

    .title-input {
        font-size: 36rpx;
        color: #333;
        padding: 20rpx;
        border: 1px solid #ddd;
        border-radius: 8rpx;
    }

    .edit-field {
        display: flex;
        align-items: center;
        gap: 8rpx;
        flex-shrink: 0;
    }

    .edit-field input {
        width: 80rpx;
        padding: 8rpx 12rpx;
        border: 1px solid #ddd;
        border-radius: 6rpx;
        text-align: center;
        font-size: 26rpx;
        background-color: #fafafa;
    }
    
    .edit-field input:focus {
        border-color: #007AFF;
        background-color: #fff;
        outline: none;
    }
    
    .unit-text {
        font-size: 24rpx;
        color: #999;
        margin-left: 4rpx;
    }

    .fixed-bottom {
        left: 0;
        right: 0;
        z-index: 100;
        padding-bottom: env(safe-area-inset-bottom);
    }
    
    .summary-edit {
        width: 100%;
        min-height: 0;
        margin-top: 10rpx;
        padding: 20rpx;
        background: transparent;
        border: 1px solid #eee;
        border-radius: 8rpx;
        font-size: 28rpx;
        box-sizing: border-box;
        overflow-y: auto;
        resize: none;
        white-space: pre-wrap;
        word-wrap: break-word;
        word-break: break-all;
        line-height: 1.6;
    }

    .module-data-edit {
        width: 80rpx;
        margin-right: 20rpx;
        padding: 4rpx;
        border: 1px solid #ddd;
        border-radius: 4rpx;
        text-align: center;
    }

    .number-input {
        font-size: 26rpx;
        color: #333;
        background: transparent;
        border: none;
        outline: none;
        width: 76rpx;
        text-align: center;
        padding: 0;
        margin-right: 20rpx;
        display: inline-block;
    }
    
    .required-field {
        border-bottom: 1px solid #ddd;
        border-radius: 4rpx;
        padding: 4rpx 8rpx;
        background-color: #fafafa;
    }
    
    .required-field:focus {
        border-bottom-color: #007AFF;
        background-color: #fff;
    }


    
    .submit-btn {
        color: #fff;
        border: none;
        border-radius: 8rpx;
        padding: 10rpx 16rpx;
        display: flex;
        align-items: center;
        gap: 6rpx;
        cursor: pointer;
        transition: all 0.2s ease;
        flex-shrink: 0;
        font-size: 24rpx;
        height: 60rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
        position: relative;
        overflow: hidden;
    }
    
    .submit-btn::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(135deg, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 50%);
        opacity: 0;
        transition: opacity 0.2s ease;
    }
    
    .submit-btn:hover {
        transform: translateY(-2rpx);
        box-shadow: 0 6rpx 16rpx rgba(0, 122, 255, 0.4);
        background: linear-gradient(135deg, #0066CC 0%, #004499 100%);
    }
    
    .submit-btn:hover::before {
        opacity: 1;
    }
    
    .submit-btn:active {
        transform: translateY(0rpx);
        box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.3);
        background: linear-gradient(135deg, #0056b3 0%, #003d82 100%);
    }
    
    .submit-text {
        font-size: 24rpx;
        color: #fff;
        font-weight: 600;
        text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
        position: relative;
        z-index: 1;
    }

    /* 响应式设计 */
    @media (min-width: 768px) {
        /* 平板和桌面样式 */
        .container {
            padding: 40rpx;
            max-width: 1200rpx;
            margin: 0 auto;
        }
        
        .header, .module-stats, .summary {
            border-radius: 16rpx;
        }
        
        .module-item {
            padding: 20rpx 50rpx;
        }
        
        .module-name {
            width: 120rpx;
        }
        
        .summary-edit {
            height: 300rpx;
        }
        
        .fixed-bottom {
            position: static;
            margin-top: 30rpx;
            box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
            border-radius: 16rpx;
        }
    }

    @media (max-width: 767px) {
        /* 移动设备样式 */
        .container {
            padding: 20rpx;
        }
        
        .module-item {
            padding: 12rpx 50rpx;
        }
        
        .summary-edit {
            height: calc(100vh - 450rpx - env(safe-area-inset-bottom));
        }
        
        .fixed-bottom {
            position: fixed;
        }
    }
</style>